//
//  ViewController.m
//  SDImage（TableView图片缓存）
//
//  Created by MyMac on 15/9/14.
//  Copyright (c) 2015年 tongfang. All rights reserved.
//

#import "ViewController.h"
#import "HFApp.h"
#import "EGOCache.h"
#import "NSString+Hashing.h"
//先判断内存中（images）有没有图片，如果有则通过key取出来显示，如果没有再去沙盒中寻找，如果沙盒中也没有，我们先显示占位图，再去创建operation下载，当然下载之前先得判断这个operation存不存在
//由于tableView的缓存机制，，，这里设计成，当tableView开始滑动时，暂停下载，，，滑动结束再恢复下载，，，
//仿SDwebImage
#define ImagePath(icon) [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[0] stringByAppendingPathComponent:icon]
@interface ViewController ()<UITableViewDataSource,UITableViewDelegate>
@property(nonatomic,strong)NSOperationQueue*queue;//存放所有下载操作的队列
@property(nonatomic,strong)NSMutableDictionary*operations;//存放所有的下载操作，key是url value是operation
@property(nonatomic,strong)NSMutableDictionary*images;//存放所有下载完成的图片，用于“内存”缓存，同样用url做key
@property(nonatomic,strong)NSMutableArray*dataArray;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.dataArray=[[NSMutableArray alloc]init];
    UITableView*tableView=[[UITableView alloc]initWithFrame:self.view.bounds];
    tableView.delegate=self;
    tableView.dataSource=self;
    
    tableView.estimatedRowHeight=60;
    tableView.rowHeight=UITableViewAutomaticDimension;
    [self.view addSubview:tableView];
    NSString*path=[[NSBundle mainBundle]pathForResource:@"apps" ofType:@"plist"];
    NSArray*array=[NSArray arrayWithContentsOfFile:path];
    
    for (NSInteger i=0; i<array.count; i++) {
        NSDictionary*dict=array[i];
        HFApp*app=[HFApp appWithDic:dict];
      
        [self.dataArray addObject:app];
        }
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataArray.count;
}
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell*cell=[tableView dequeueReusableCellWithIdentifier:@"ll"];
    if (cell==nil) {
        cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"ll"];
    }
    
    HFApp*app=self.dataArray[indexPath.row];
    cell.textLabel.text=app.name;
    cell.detailTextLabel.text=app.download;
    UIImage*image=self.images[app.icon];
    __weak typeof(self) vc=self;
    NSLog(@"   %@",ImagePath(app.icon));
    if (image) {
        //内存中如果图片存在就从内存中取
        cell.imageView.image=image;
    }else{
    //内存中图片不存在就从沙盒中取
       // image=[UIImage imageWithContentsOfFile:ImagePath([[app.icon MD5Hash]stringByAppendingString:@".png"])];
        image=[[EGOCache globalCache]imageForKey:app.icon];
        if(image){
            //沙盒中如果图片存在就呈现
            cell.imageView.image=image;
        
        }else {
            //显示占位图
            cell.imageView.image=[UIImage imageNamed:@"placeholder"];
        //沙盒中如果图片不存在就下载
            NSBlockOperation*operationImage=self.operations[app.icon];
//            NSLog(@"%@",app.icon);
            if(!operationImage){
            //如果下载的operation不存在就创建，并加入到queue和operations字典中
                operationImage=[NSBlockOperation blockOperationWithBlock:^{
                  
                    NSData*data=[NSData dataWithContentsOfURL:[NSURL URLWithString:app.icon]];
                    if (data) {
                        //防止下载失败，做的判断
                        UIImage*cacaeImage=[UIImage imageWithData:data];
                        //照片下载完后存入缓存
                        [vc.images setObject:cacaeImage forKey:app.icon];
                        //存入沙盒
                        //BOOL ret= [data writeToFile:ImagePath([[app.icon MD5Hash] stringByAppendingString:@".png"]) atomically:YES];
                        [[EGOCache globalCache]setImage:cacaeImage forKey:app.icon   withTimeoutInterval:24*60*60];
                        //NSLog(@"%ld",(long)ret);
                           //cell.imageView.image=cacaeImage;
                        //主线程刷新
                        [[NSOperationQueue mainQueue]addOperationWithBlock:^{
                            [vc.operations removeObjectForKey:app.icon];
                        [tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
                        }];
                        }
                  }];
                [self.queue addOperation:operationImage];
                [self.operations setObject:operationImage forKey:app.icon];
            }
        }
    }
    return cell;
}
-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
//当开始滑动时暂停队列中任务的调配，但当前已经执行的任务还是会执行，他只会暂停还没有开始的任务
    [self.queue setSuspended:YES];

}
-(void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{

    [self.queue setSuspended:NO];
}



-(NSOperationQueue*)queue
{
    if (!_queue) {
        _queue=[[NSOperationQueue alloc]init];
    }
    return _queue;
}

-(NSMutableDictionary*)images
{

    if (_images) {
        _images=[[NSMutableDictionary alloc]init];
    }
    return _images;

}
-(NSMutableDictionary*)operations
{
    if(!_operations){
    
        _operations=[[NSMutableDictionary alloc]init];
    }
    return _operations;

}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    [self.queue cancelAllOperations];
    [self.images removeAllObjects];
    [self.operations removeAllObjects];
}

@end
